package com.mitu.nio.gruopchat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

public class GroupChatClient {
    private final String HOST = "127.0.0.1";    //服务器IP
    private final int HOST_PORT = 6667;         //服务器端口
    private Selector selector;
    private SocketChannel socketChannel;

    private String USERNAME;

    //完成初始化工作
    public GroupChatClient() throws IOException {
        selector = Selector.open();
        //连接服务器
        socketChannel = SocketChannel.open(new InetSocketAddress(HOST, HOST_PORT));
        //设置非阻塞
        socketChannel.configureBlocking(false);
        //将Channel注册到Selector
        socketChannel.register(selector, SelectionKey.OP_READ);
        //得到username
        USERNAME = socketChannel.getLocalAddress().toString().substring(1);
        System.out.println(USERNAME + "is ok...");
    }

    //向服务器发送消息
    public void sendInfo(String info) {
        info = USERNAME + "说:" + info;
        try {
            //发送消息
            socketChannel.write(ByteBuffer.wrap(info.getBytes(StandardCharsets.UTF_8)));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //从服务器端接收消息
    public void readInfo() {
        try {
            int readChannel = selector.select(2000);
            if (readChannel > 0) {
                //有通道有新的事件
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    //从iterator获取到SelectionKey
                    SelectionKey key = iterator.next();
                    if (key.isReadable()) {
                        //得到相关的通道
                        SocketChannel readSocketChannel = (SocketChannel) key.channel();
                        //得到一个buffer
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        //读取
                        readSocketChannel.read(buffer);
                        String message = new String(buffer.array());
                        System.out.println(message.trim());
                    }
                }
                //删除当前的selectionKey,防止出现重复操作
                iterator.remove();
            } else {
                //System.out.println("没有可以用的通道...");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) throws IOException {
        //启动客户端
        GroupChatClient client = new GroupChatClient();
        //启动一个线程,每隔3秒读取服务器端发送得到数据
        new Thread() {
            @Override
            public void run() {
                while (true) {
                    client.readInfo();
                    try {
                        Thread.currentThread().sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();

        //客户端发送数据给服务器端
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            String s = scanner.nextLine();
            client.sendInfo(s);
        }
    }
}
